/**
 * lhj
 */
import chalk from 'chalk'
import Rsa from './Rsa'

export default class MRsa{

    public static getKeys(keysPath: string) {
        const rsa = new Rsa()
        // rsa.getKeys()
        console.log(rsa.getKeys())
        rsa.output(keysPath)
        process.exit(0)
    }


    public static encryptByPubKey(data: string, pubKeyPath?: string, keysPath?: string) {
        let pubKey = null
        if (pubKeyPath) pubKey = Rsa.getKey(pubKeyPath)
        else {
            if (keysPath) {
                // pub pri
                pubKey = MRsa.getKey(keysPath, '-----END PUBLIC KEY-----')
            } else {
                console.log(chalk.red('请指定 --pub 或 -ksp 参数'))
            }
        }
        const rsa = new Rsa()
        console.log(rsa.encryptByPubKey(data, pubKey as string))
    }

    public static decryptByPriKey(data: string, priKeyPath?: string, keysPath?: string) {
        let priKey = null
        if (priKeyPath) priKey = Rsa.getKey(priKeyPath)
        else {
            if (keysPath) {
                // pub pri
                priKey = MRsa.getKey(keysPath, '-----END PRIVATE KEY-----')
            } else {
                console.log(chalk.red('请指定 --pri 或 -ksp 参数'))
            }
        }
        const rsa = new Rsa()
        console.log(rsa.decryptByPriKey(data, priKey as string))
    }

    public static signature(data: string, priKeyPath?: string, keysPath?: string) {
        let priKey = null
        if (priKeyPath) priKey = Rsa.getKey(priKeyPath)
        else {
            if (keysPath) {
                // pub pri
                priKey = MRsa.getKey(keysPath, '-----END PRIVATE KEY-----')
            } else {
                console.log(chalk.red('请指定 --pri 或 -ksp 参数'))
            }
        }
        const rsa = new Rsa()
        console.log(rsa.signature(data, priKey as string))
    }

    public static verify(data: string, verify: string, pubKeyPath?: string, keysPath?: string) {
        let pubKey = null
        if (pubKeyPath) pubKey = Rsa.getKey(pubKeyPath)
        else {
            if (keysPath) {
                // pub pri
                pubKey = pubKey = MRsa.getKey(keysPath, '-----END PUBLIC KEY-----')
            } else {
                console.log(chalk.red('请指定 --pub 或 -ksp 参数'))
            }
        }
        const rsa = new Rsa()
        console.log(rsa.verify(data, verify, pubKey as string))
    }

    private static getKey(keysPath: string, flag: string): string {
        let pubKey = Rsa.getKey(keysPath)
        pubKey = pubKey.substring(0, pubKey.indexOf(flag) + flag.length)
        return pubKey
    }
}